// UI相关代码

// 简单调色板（可根据聚类数扩展）
const COLOR_PALETTE = [
    Cesium.Color.RED, Cesium.Color.BLUE, Cesium.Color.GREEN, 
    Cesium.Color.ORANGE, Cesium.Color.YELLOW,
    Cesium.Color.PURPLE, Cesium.Color.CYAN, Cesium.Color.MAGENTA, 
    Cesium.Color.BROWN, Cesium.Color.LIME
];

/**
 * 在 Cesium 中绘制聚类边
 * @param {Array} clusteredEdges - 每个元素是边数组（形如 [[from, to], ...]）
 * @param {Array} nodes - 节点数组，每个含 id, lon, lat
 * @param {Viewer} viewer - Cesium Viewer 实例
 */
export function drawClusteredEdges(clusteredEdges, nodes, viewer) {
    const entities = [];

    const nodeMap = Object.fromEntries(nodes.map(n => [n.id, n]));
    clusteredEdges.forEach((edges, clusterIndex) => {
        const color = COLOR_PALETTE[clusterIndex % COLOR_PALETTE.length];

        edges.forEach(([from, to]) => {
            const p1 = nodeMap[from];
            const p2 = nodeMap[to];
            if (!p1 || !p2) return;

            let e = viewer.entities.add({
                    polyline: {
                        positions: Cesium.Cartesian3.fromDegreesArray([
                            p1.lon, p1.lat,
                            p2.lon, p2.lat
                        ]),
                        width: 1.0,
                        material: color.withAlpha(0.5)
                    }
                });
            entities.push(e);
        });
    });

    return entities;
}



/**
 * 在 Cesium 场景中渲染骨架线段
 * @param {Cesium.Viewer} viewer - Cesium 视图对象
 * @param {{ [clusterId: number]: Array<[[number, number], [number, number]]> }} skeletons - 骨架线段集合
 */
export function drawSkeletons(skeletons, viewer) {
    const entities = [];

    for (const [clusterIdStr, lines] of Object.entries(skeletons)) {
        const clusterId = parseInt(clusterIdStr);
        const color = COLOR_PALETTE[clusterId % COLOR_PALETTE.length];

        for (const [[lon1, lat1], [lon2, lat2]] of lines) {
            let e = viewer.entities.add({
                polyline: {
                    positions: Cesium.Cartesian3.fromDegreesArray([lon1, lat1, lon2, lat2]),
                    width: 8,
                    material: color.withAlpha(0.8)
                }
            });
            entities.push(e);
        }
    }

    return entities;
}

/**
 * 在 Cesium 场景中渲染warpedEdges
 * @param {Cesium.Viewer} viewer - Cesium 视图对象
 * @param {Array} bindings - 每条边绑定信息 { edge, midpoint, nearest }
 * @param {Array} warpedEdges - 每条边的插值路径，如 [[p0, p1, p2, ...], ...]
 */
export function drawWarpedEdges(warpedEdges, bindings, viewer) {
    const entities = [];

    warpedEdges.forEach((path, index) => {
        const binding = bindings[index];
        const clusterId = parseInt(binding.clusterId);
        const color = COLOR_PALETTE[clusterId % COLOR_PALETTE.length];

        const positions = path.flatMap(([lon, lat]) =>
            Cesium.Cartesian3.fromDegreesArray([lon, lat])
        );
        let e = viewer.entities.add({
            name: `Cluster ${clusterId} Edge ${index}`,
            polyline: {
                positions: positions,
                width: 1.5,
                material: color,
                clampToGround: false,
            },
        });
        entities.push(e);
    });

    return entities;
}

export function drawFDEBEdges(edges, viewer) {
  const entities = [];
  for (const edge of edges) {
    const positions = edge.subdivisionPoints.map(p =>
      Cesium.Cartesian3.fromDegrees(p.lon, p.lat)
    );
    const e = viewer.entities.add({
      polyline: {
        positions,
        width: 1.5,
        material: Cesium.Color.ORANGE.withAlpha(0.8),
      },
    });
    entities.push(e);
  }
  return entities;
}



export function toggleBtnContent(button) {
  const content = button.textContent;
  if (content.includes('显示')) {
    button.textContent = content.replace('显示', '隐藏');
  } else if (content.includes('隐藏')) {
    button.textContent = content.replace('隐藏', '显示');
  }
}


export function setupUI(callbacks) {
    document.getElementById("btn-cluster").onclick = callbacks.onCluster;
    document.getElementById("btn-skeleton").onclick = callbacks.onSkeleton;
    document.getElementById("btn-warp").onclick = callbacks.onWarp;
    document.getElementById("btn-run-fdeb").onclick = callbacks.onRunFDEB;
    document.getElementById("btn-fdeb").onclick = callbacks.onFDEB;
    document.getElementById("btn-reset").onclick = callbacks.onReset;
}
